/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.st.socket.server.netty;

import java.nio.ByteBuffer;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ChildChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bambamboo.st.IProcessor;
import com.bambamboo.st.util.HexString;

/**
 * DOCME
 * 
 * @author Nick.Tan
 * @since 1.0.0
 */
@ChannelPipelineCoverage("all")
public class DefaultChannelHandler extends AbstractChannelHandler {

	private static final Logger logger = LoggerFactory.getLogger(DefaultChannelHandler.class);

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
		ChannelBuffer buffer = (ChannelBuffer) event.getMessage();
		IProcessor processor = getConfigurationBean().getProcessor();
		ByteBuffer buf = buffer.toByteBuffer();
		byte[] requestBuf = new byte[buf.limit()];
		buf.get(requestBuf);
		logger.debug("request data from <{}>:\n{}", ctx.getChannel().getRemoteAddress(), HexString.dump(requestBuf));

		byte[] byResp = processor.getResponse(requestBuf);
		if (byResp != null && byResp.length > 0) {
			ChannelBuffer out = ChannelBuffers.buffer(byResp.length);
			out.writeBytes(byResp);
			event.getChannel().write(out);
		}
	}

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelClosed(ctx, e);
		logger.info(">>>>> status: channelClosed: " + ctx.getChannel().getRemoteAddress());
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelConnected(ctx, e);
		logger.info(">>>>> status: channelConnected: " + ctx.getChannel().getRemoteAddress());
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelDisconnected(ctx, e);
		logger.info(">>>>> status: channelDisconnected: " + ctx.getChannel().getRemoteAddress());
	}

	@Override
	public void childChannelClosed(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception {
		super.childChannelClosed(ctx, e);
		logger.info(">>>>> status: childChannelClosed: " + ctx.getChannel().getRemoteAddress());
	}

}
